package client

import (
	"bufio"
	"encoding/json"
	"fmt"
	"io"
	"log"
	"net"
	"os"
	"strings"
	"time"
	_struct "websocket/struct"
)

func Start() {
	var name string
	var err error
	for {
		fmt.Print("请输入你的用户名字:")
		reader := bufio.NewReader(os.Stdin)
		name, err = reader.ReadString('\n')
		if err != nil || name == "\n"{
			fmt.Println("读取名字失败,请重新输入")
			continue
		}
		fmt.Print("你输入的用户名是:"+ name)
		break
	}
	name = strings.TrimRight(name,"\n")
	conn, err := net.Dial("tcp", "127.0.0.1:8888")
	if err != nil {
		log.Fatal(err)
	}
	done := make(chan struct{})
	var massage _struct.Message
	go func() {
		reader := bufio.NewReader(conn)
		for {
			text, err := reader.ReadString('\n')
			//fmt.Println("接收服务端数据:",string(text))
			if err != nil{
				fmt.Println("服务器已断开")
				break
			}
			text = strings.TrimRight(text,"\n")
			// 数据为空则关闭
			if text == ""{
				continue
			}
			err = json.Unmarshal([]byte(text),&massage)
			//fmt.Println("解析数据:",massage)
			if err != nil{
				fmt.Println("数据解析错误", text, err)
			}else{
				if massage.Name == name && massage.SendType == "send_msg"{
					continue
				}
				fmt.Println("【"+ massage.Name + "】"+ "(说:" + massage.Content)
			}
			continue
		}
		//io.Copy(os.Stdout, conn) // 阻塞
		log.Println("done")
		done <- struct{}{} // 向主Goroutine发出信号
	}()
	mustCopy(conn, os.Stdin, name)

	conn.Close()
	<-done // 等待后台goroutine完成
	return
}

// 操作
func mustCopy(dst io.Writer, src io.Reader,name string) {
	reader := bufio.NewReader(src)
	writer := bufio.NewWriter(dst)

	var massage _struct.Message

	sendMsg(writer,massage,name + "登陆",name,"login")
	//fmt.Println("组装数据:",massage)
	//fmt.Println("json数据:",string(msgJson))
	// 心跳
	go sendHeartbeat(writer,massage,name,name,"heartbeat")
	for {
		text, err := reader.ReadString('\n')
		if err != nil{
		}
		if text == "\n"{
			continue
		}
		text = strings.TrimRight(text,"\n")
		//fmt.Println("读取控制台数据:",text)
		sendMsg(writer,massage,text,name,"send_msg")
	}
	//if _, err := io.Copy(dst, src); err != nil {
	//	log.Fatal(err)
	//}
}

// 发送消息
func sendMsg(writer *bufio.Writer,massage _struct.Message,content string ,name string,sendType string) {
	massage.Content = content
	massage.Name = name
	massage.SendType = sendType
	msgJson, err := json.Marshal(massage)
	if err != nil{
		fmt.Println("封装数据有问题")
		return
	}
	//fmt.Println("组装数据:",massage)
	//fmt.Println("json数据:",string(msgJson))
	// 组装数据
	str := string(msgJson) + "\n"
	writer.WriteString(str)
	writer.Flush()
}

// 发送心跳
func sendHeartbeat(writer *bufio.Writer, massage _struct.Message, content string, name string, sendType string) {
	for {
		sendMsg(writer, massage, name, name, sendType)
		time.Sleep(time.Second * 2)
	}
}